!(function ($) {

  $.cachedScript = function (url, options) {

    options = $.extend(options || {}, {
      dataType: 'script',
      cache: true,
      url: url
    });

    return $.ajax(options);
  };

  var authToken = null;
  var username = $.trim($('.top-welcome-name').text());

  // 插入样式
  $('head').append('<link rel="stylesheet" href="/webim/css/msg.min.css">');
  $.cachedScript("/webim/js/list.js");
  
  (function () {    // 如果没有JSON对象，加载JSON兼容库
    var dfd = $.Deferred();
    return JSON ? dfd.resolve() : $.cachedScript('/webim/lib/json3/lib/json3.min.js');
  })()
    .then(function () {       // 如果不支持ES5，加载ES5-SHIM
      if (!Array.prototype.forEach) {
        console.log('Array不支持forEach方法，加载es5-shim..');
        return $.cachedScript('/webim/lib/es5-shim/es5-shim.min.js');
      }
    })
    .then(function () {
      console.log('加载socket.io库..');
      return $.cachedScript('/webim/lib/socket.io-client/socket.io.js');
    })
    .then(function () {
      console.log('加载md5库..');
      return $.cachedScript('/webim/lib/JavaScript-MD5/js/md5.min.js');
    })
    .then(function () {   // 获取用户token
      console.log('权限校验..');
      var dfd = $.Deferred();
      var $authFrame = $('<iframe src="/msg/pages/auth" name="authFrame">');
      $authFrame.hide();
      $authFrame.appendTo('body');
      $authFrame.on('load', function () {
        try {
          var authWindow = $authFrame[0].contentWindow;
          var token = authWindow.document.body.innerText;
          dfd.resolve(token);
        } catch (e) {
          console.log('用户未登录', e);
          dfd.reject(e);
        }
      });
      return dfd;
    })
    .then(function (token) {
      console.log('权限校验通过,开始连接..');
      authToken = token;
      var uid = username;
      var timestamp = new Date().getTime();
      var signature = md5([uid, token, timestamp].join('').split('').sort().join(''));
      var query = ['uid=', uid, '&timestamp=', timestamp, '&signature=', signature].join('');
      return io('http://' + location.host + '?' + query, { path: '/msg/socket.io' });
    })
    .then(function (socket) {
      socket.on('connect', function () {
        console.log('socket.io 连接成功');
      });
      socket.on('disconnect', function (data) {
        console.log('断开连接', data);
      });
      socket.on('message', function (data) {
        console.log('收到 socket.io 新消息', data);

        // CassMessage 必须为 object 切不为null
        if (window.CassMessage && typeof window.CassMessage === 'object') {
          var onReceived = window.CassMessage.onReceived;
          if (typeof onReceived === 'function') {
            onReceived(data);
          }
        }

        //有新消息触发更新未读消息
        getUnreadMessage();
        //侧边栏消息中心跳动
        if (!timer) {
          flipMsgCenter();
        }
      });

      var $btn = $('.quick_links_panel .history_list');
      $btn.closest('li').removeAttr('onclick').on('click', function () {
        window.open('/portal/messageCenter', '_blank');
      });
      var $sideBtn = $btn.css('position', 'relative');
      var $dot = $('<span class="dot hide"></span>');

      $dot.css({
        position: 'absolute',
        top: '7px',
        left: '24px',
        color: '#e22e33',
        width: '8px',
        'border-radius': '50%',
        height: '8px',
        background: 'red'
      });
      $dot.appendTo($sideBtn);

      //获取插件元素
      var $nav = $('.nav-message');

      var navTemp = '<a href="/portal/messageCenter"  target="_blank">' +
        '<i class="icon icon-8"></i>消息中心&nbsp;' +
        '<span class="nav-badge"></span></a>';


      // 覆盖原有内容
      $nav.html(navTemp);

      //登录成功后执行一次，获取未读消息
      getUnreadMessage();

      window.updateMsgCount = getUnreadMessage;

      /**
       * ajax请求未读消息
       */
      function getUnreadMessage() {
        var timestamp = new Date().getTime();
        var signature = md5([username, authToken, timestamp].join('').split('').sort().join(''));
        var query = ['uid=', username, '&timestamp=', timestamp, '&signature=', signature].join('');

        $.ajax({
          type: 'GET',
          url: '/msg/api/messages?isRead=false&' + query,
          cache: false,
          success: updateList,
          error: function (err) {
            console.log('请求失败', err);
          }
        });
      }

      /**
       * 更新消息列表
       * @param messages
       */
      function updateList(messages) {
        console.log('成功返回未读消息：', messages);
        var count = messages.length;
        $nav.find('.nav-badge').text(count);
        if (count == 0) {
          stopMsgCenterFlip();
        }
        if (count && !timer) {
          flipMsgCenter();
        }
      }
    })
    .fail(function (err) {
      console.error('执行出错', err);
    });


  var timer = null;

  function flipMsgCenter() {
    $('.quick_links_panel .history_list .dot').removeClass('hide');
    var flip = true;
    timer = setInterval(function () {
      $('.quick_links_panel .history_list').css('visibility', flip ? 'hidden' : 'visible');
      flip = !flip;
    }, 500);
  }

  function stopMsgCenterFlip() {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
    // 删除小红点
    $('.quick_links_panel .history_list')
      .css('visibility', 'visible')
      .find('.dot').addClass('hide');
  }

  function getLastestMessageSentTime() {
    return parseInt(localStorage.getItem('rong-msg-sent-time'));
  }
})(jQuery);

